import os
import sys
import logging
from logging import handlers

from .settings import LOG_DIR


level_relations = {
        'debug':logging.DEBUG,
        'info':logging.INFO,
        'warning':logging.WARNING,
        'error':logging.ERROR,
        'critical':logging.CRITICAL
    }#日志级别关系映射
fmt = '%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'
filename = os.path.join(LOG_DIR, 'logs.log')

class Logger(object):
    def __init__(self, filename=filename, level='debug', fmt=fmt):
        self.logger = logging.getLogger(filename)
        self.logger.handlers.clear()
        format_str = logging.Formatter(fmt)   #设置日志格式
        self.logger.setLevel(level_relations.get(level))   #设置日志级别
        self.sh_handler = logging.StreamHandler()   #往屏幕上输出
        self.sh_handler.setFormatter(format_str)   #设置屏幕上显示的格式
        self.fp_handler = handlers.RotatingFileHandler(filename=filename, encoding='utf-8')   #往文件里写入
        self.fp_handler.setFormatter(format_str)   #设置文件里写入的格式
        self.logger.addHandler(self.sh_handler)   #把对象加到logger里
        self.logger.addHandler(self.fp_handler)

        self.debug = self.logger.debug
        self.info = self.logger.info
        self.warning = self.logger.warning
        self.error = self.logger.error
        self.critical = self.logger.critical


logger = Logger()